package edu.biwu.response;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * HttpServletResponse中的方法
 *  getOutputStream():获取一个字节输出流
 * ServletContext中的方法
 *   getMimeType(String fileName):根据指定的名称返回对应的MIME类型
 */
@WebServlet("/resp/demo05")
public class ResponseDemo05 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置字符输出流,并通过缓存包装一下
        ServletOutputStream os = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(os);
        //设置响应内容的MIME类型
        String mimeType = getServletContext().getMimeType("1.jpg");
        //设置响应内容的MIME类型
        //告知浏览器响应内容的MIME类型,让浏览器知道如何处理
        response.setHeader("Content-Type",mimeType);

        //通过字节输出流将字节写给浏览器
        InputStream is = getServletContext().getResourceAsStream("/1.jpg");
        BufferedInputStream bis = new BufferedInputStream(is);
        int b;
        while((b=bis.read())!=-1){
        bos.write(b);
        }
    }

        @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
